#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2025/6/17 21:37
# @Author  : wuyupeng
# @FileName: obs_apt_repo_manager.py
# @Software: PyCharm
import os
import sys
import logging
from tqdm import tqdm
from pathlib import Path

from repo_uploaders.repo_manager import RepoManagerFactory
from repo_uploaders.impls.apt_repo_manager import AptRepoManager, PipeLineLogHelper

SCRIPTS_PATH = Path(__file__).resolve().parents[5]
if SCRIPTS_PATH not in sys.path:
    sys.path.append(SCRIPTS_PATH.as_posix())

from utils.common import func_retry
from utils.obs_helper import ObsHelper

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")


class OBSPipeLineLogHelper(PipeLineLogHelper):
    def __init__(self, ak, sk, obs_endpoint, obs_bucket_name):
        self.obs_helper = ObsHelper(ak, sk, obs_endpoint)
        self.obs_bucket_name = obs_bucket_name

    @func_retry()
    def upload_foler(self, local_path: Path, remote_key: str = ""):
        for root_dir, _, files in os.walk(str(local_path)):
            root = Path(root_dir)
            for fn in tqdm(files, desc="Uploading files"):
                local_file = root / fn
                remote_key = local_file.relative_to(local_path).as_posix()
                try:
                    self.obs_helper.upload_file(self.obs_bucket_name, remote_key, local_file.resolve())
                except Exception as e:
                    logging.error(f"Faild to upload {local_file}: {str(e)}")

    @func_retry()
    def get_file(self, remote_key, download_path):
        return self.obs_helper.get_object(self.obs_bucket_name, remote_key, download_path)

    @func_retry()
    def upload_file(self, remote_key: str, local_file: str):
        return self.obs_helper.upload_file(self.obs_bucket_name, remote_key, local_file)

    @func_retry()
    def delete_file(self, remote_key: str):
        return self.obs_helper.delete_object(self.obs_bucket_name, remote_key)


@RepoManagerFactory.register("obs")
class OBSAptRepoManager(AptRepoManager):
    def init_apt_helper(self, ak, sk, endpoint, bucket_name):
        self.apt_helper = OBSPipeLineLogHelper(ak, sk, endpoint, bucket_name)
